﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Net;
using System.Text.RegularExpressions;
using System.Configuration;

namespace CSharp.Infrastructure
{
    /// <summary>
    /// CMD命令管理器
    /// </summary>
    public class CmdHelper
    {
        public CmdHelper()
        {
        }

        /// <summary>
        /// 通过ping命令测试网络是否通
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool TestConnection(string ip)
        {
            try
            {
                System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                if (ping.Send(ip).Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    return true;
                }
            }
            catch (Exception Ex)
            {
                Debug.Assert(false, Ex.ToString());
            }

            return false;
        }

        /// <summary>
        /// 执行命令，读取结果
        /// </summary>
        /// <returns></returns>
        public string ReadProecssMsg(string args)
        {
            string content = string.Empty;
            try
            {
                Process myProcess = new Process();
                myProcess.StartInfo.CreateNoWindow = false;
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.RedirectStandardInput = true;
                myProcess.StartInfo.RedirectStandardOutput = true;
                myProcess.StartInfo.FileName = "cmd.exe";
                myProcess.Start();
                myProcess.StandardInput.WriteLine(args);
                myProcess.StandardInput.WriteLine("exit");
                myProcess.WaitForExit();
                content = myProcess.StandardOutput.ReadToEnd();

                myProcess.Close();
            }
            catch (Exception Ex)
            {
                Debug.Assert(false, Ex.ToString());
            }

            return content;
        }
    }
}
